<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar draft'">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-form-item style="margin-bottom: 40px;" label-width="80px" label="任务名称:">
          <el-input :rows="1" v-model="postForm.name" autosize placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="80px" label="发布总数:">
          <el-input :rows="1" v-model="postForm.entry" autosize placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="80px" label="发布数量:">
          <el-input :rows="1" v-model="postForm.num" autosize placeholder="请输入内容"/>
        </el-form-item>

        <el-col :span="10">
          <el-form-item label-width="80px" label="发布时间:" class="postInfo-container-item">
            <el-time-picker v-model="postForm.time" type="datetime" format="HH:mm:ss" placeholder="选择日期时间"/>
          </el-form-item>
        </el-col>

        <div v-if="postForm.id == undefined">
          <el-upload
            :headers="myHeaders"
            :multiple="false"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            name="excel"
            action="/api/backstage/company/task/upload"
            class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
            <div v-if="fileName" slot="tip" class="el-upload__tip">文件名：{{ fileName }}</div>
          </el-upload>
        </div>
      </div>
    </el-form>

  </div>
</template>

<script>
import Sticky from '@/components/Sticky' // 粘性header组件
import { create, firstId, update } from '@/api/backstage/company/upload'
import { getToken } from '@/utils/auth'

const defaultForm = {
  time: '',
  name: '', // 任务名称
  entry: '', // 文章内容
  num: '', // 文章摘要
  path: '', // 文章图片
  id: undefined
}

export default {
  name: 'ArticleDetail',
  components: { Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      const errorFile = {
        name: '名称',
        entry: '发布总数',
        num: '发布数量',
        path: '导入文件'
      }
      if (value === '') {
        this.$message({
          message: errorFile[rule.field] + '为必传项',
          type: 'error'
        })
        callback(new Error(errorFile[rule.field] + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      fileName: '',
      myHeaders: { Authorization: 'Bearer ' + getToken() },
      postForm: Object.assign({}, defaultForm),
      loading: false,
      categoryListOptions: [],
      rules: {
        name: [{ validator: validateRequire }],
        entry: [{ validator: validateRequire }],
        num: [{ validator: validateRequire }],
        path: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    emitInput(val) {
      this.postForm.path = val
    },
    handleImageSuccess(file) {
      this.fileName = file.data.name
      this.emitInput(file.data.disk)
    },
    beforeUpload() {
    },
    fetchData(id) {
      firstId(id).then(response => {
        this.postForm = response.data
        // Set tagsview title
        this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑任务' : 'Edit Article'
      this.postForm.time = new Date('2019/12/12 ' + this.postForm.time)
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.name}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid && this.loading === false) {
          this.loading = true
          var d = new Date(this.postForm.time)
          const data = {
            name: this.postForm.name,
            entry: this.postForm.entry, // 文章内容
            path: this.postForm.path, // 文章摘要
            num: this.postForm.num, // 文章图片
            time: d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
          }
          if (this.postForm.id !== undefined) {
            const id = this.postForm.id
            update(data, id).then(() => {
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.push('/company/uploads')
            })
          } else {
            console.log(data)
            create(data).then(() => {
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.push('/company/uploads')
            })
          }
        } else {
          this.loading = false
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
